package com.hyl.crmclient.service;

import com.hyl.jpademo.dao.ChanceRepostory;
import com.hyl.jpademo.entity.Chance;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/5/25 16:22
 **/
@Service("chanceService")
public class ChanceServiceImpl implements ChanceService {

	@Resource
	ChanceRepostory chanceRepostory;

//	@Resource
//	StringRedisTemplate stringRedisTemplate;

	//@Cacheable(value = "chance", keyGenerator = "keyGenerator")
	@Override
	public Page<Chance> findPageByParam(Map<String,String> param, Pageable pageable) {

//		boolean bool = stringRedisTemplate.hasKey("test");
		//判断redis中是都存在==》存在，从redis中获取
//		if(bool){
//			String val = stringRedisTemplate.opsForValue().get("test"); //json
//			return null;
//		}else {
//			//如果不存在，从数据库中获取，然后写入到redis里面
//			stringRedisTemplate.opsForValue().set("test", "test");

			Page<Chance> page = chanceRepostory.findAll(new Specification<Chance>() {
				@Override
				public Predicate toPredicate(Root<Chance> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
					//用于添加条件的集合对象
					List<Predicate> predicates = new ArrayList<>();
					if (param.get("custName") != null && !param.get("custName").equals("")) { //动态 SQL
						predicates.add(criteriaBuilder.like(root.get("custName"), "%" + param.get("custName") + "%"));
					}
					if (param.get("title") != null && !param.get("title").equals("")) {
						predicates.add(criteriaBuilder.equal(root.get("chcTitle"), param.get("title")));
					}
					return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
				}
			}, pageable);
			return page;
//		}
	}

	@Cacheable(value = "chance", keyGenerator = "keyGenerator")
	@Override
	public List<Chance> findAll() {
		return chanceRepostory.findAll();
	}
}
